package cn.jy.careuplusdoctor.utils;

import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import org.apache.http.entity.mime.MultipartEntity;

/**
* 带进度条的
* @Title: ProgressMultipartEntity.java
* @Package com.gzedu.utils
* @Description: TODO
* @date 2015-1-4 下午3:14:43
* @version V1.0
 */
public class ProgressMultipartEntity extends MultipartEntity {
	
	private ProgressCallback progressCallback;
	
	public ProgressCallback getProgressCallback() {
		return progressCallback;
	}

	public void setProgressCallback(ProgressCallback progressCallback) {
		this.progressCallback = progressCallback;
	}

	@Override
	public void writeTo(OutputStream outstream) throws IOException {
		if(progressCallback==null){
			super.writeTo(outstream);
		}else{
			super.writeTo(new ProgressOutputStream(outstream, progressCallback));
		}
	}
	
	/**
	* 进度回调
	* @Title: ProgressMultipartEntity.java
	* @Package com.gzedu.utils
	* @Description: 进度回调
	* @company:		EE教育有限公司
	* @author :		Eriksson
	* @date 2015-1-4 下午3:14:13
	* @version V1.0
	 */
	public static interface ProgressCallback{
		
		/**
		 * 进度
		 * @param percentage
		 */
		public void progress(long percentage);
		
	}
	
	public static class ProgressOutputStream extends FilterOutputStream{

		private ProgressCallback progressCallback;
		private long progress = 0l;
		
		public ProgressCallback getProgressCallback() {
			return progressCallback;
		}

		public void setProgressCallback(ProgressCallback progressCallback) {
			this.progressCallback = progressCallback;
		}
		
		public ProgressOutputStream(OutputStream out,ProgressCallback progressCallback) {
			super(out);
			this.progressCallback = progressCallback;
			this.progress = 0l;
		}
		
		public void write(byte[] b, int off, int len) throws IOException{
			out.write(b, off, len);
			if(this.progressCallback==null){
				return;
			}
			this.progress += len;
			this.progressCallback.progress(this.progress);
		}
 
		public void write(int b) throws IOException
		{
			out.write(b);
			this.progress++;
			if(this.progressCallback==null){
				return;
			}
			this.progressCallback.progress(this.progress);
		}
		
	}
}
